package com.edwin.websitebe.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edwin.websitebe.model.News;
import com.edwin.websitebe.service.NewsService;
import com.edwin.websitebe.util.OSSUtil;
import com.edwin.websitebe.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/news")
@Slf4j
public class NewsController {

    @Autowired
    private NewsService service;

    @GetMapping("")
    public ResultVO list(News news) {

        Page<News> page = service.pageList(news);

        return new ResultVO().success(page);
    }

    @PostMapping("")
    public ResultVO saveOrUpdate(@RequestBody News news) {
        boolean result = service.saveOrUpdate(news);
        return result ? new ResultVO().success() : new ResultVO().fail();
    }

    @GetMapping("/getById/{id}")
    public ResultVO getById(@PathVariable("id") Long id) {
        News news = service.getById(id);
        return new ResultVO().success(news);
    }

    @DeleteMapping("/delete")
    public ResultVO delete(@RequestParam Long id) {
        boolean result = service.removeById(id);
        return new ResultVO().success();
    }

    @PostMapping("/uploadCover")
    public ResultVO uploadCover(MultipartFile file, @RequestParam String id, HttpServletRequest request) throws IOException {
        log.info("开始上传新闻封面: newsId: {}", id);
        String filename = file.getOriginalFilename();
        String extend = filename.substring(filename.lastIndexOf("."));
        String objName = "img/news/" + id + "-" + IdUtil.simpleUUID() + "-cover" + extend;
        String url = OSSUtil.uploadFile(objName, file);
        log.info("新闻封面上传完成: newsId: {}, url: {}", id, url);
        log.info("开始更新新闻数据");
        News news = service.getById(id);
        news.setImgUrl(url);
        service.updateById(news);
        return new ResultVO().success();
    }

}
